package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;

import com.zzyl.dto.ResourceDto;
import com.zzyl.entity.Resource;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.ResourceMapper;
import com.zzyl.service.ResourceService;
import com.zzyl.utils.NoProcessing;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.ResourceVo;
import com.zzyl.vo.TreeItemVo;
import com.zzyl.vo.TreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Service
public class ResourceServiceimpl implements ResourceService {
    @Autowired
    private ResourceMapper resourceMapper;

    /**
     * 资源列表
     *
     * @param resourceDto
     * @return
     */
    @Override
    public List<ResourceVo> resourceList(ResourceDto resourceDto) {
        Resource bean = BeanUtil.toBean(resourceDto, Resource.class);
        List<ResourceVo> resourceVoList = resourceMapper.resourceList(bean);
        return resourceVoList;
    }

    /**
     * 资源树型
     *
     * @param resourceDto
     * @return
     */
    @Override
    public TreeVo resourceTree(ResourceDto resourceDto) {
        //查询所有菜单
        Resource bean = BeanUtil.toBean(resourceDto, Resource.class);
        bean.setResourceType("m");
        bean.setDataState("0");
        List<ResourceVo> resourceVoList = resourceMapper.resourceList(bean);

        //封装所有数据
        List<TreeItemVo> treeItemVos = new ArrayList<>();

        //根目录
        ResourceVo root = new ResourceVo();
        root.setResourceNo("100001000000000");
        root.setResourceName("智慧养老院");

        //递归调用
        recursionTree(treeItemVos, root, resourceVoList);
        TreeVo treeVo = new TreeVo();
        treeVo.setItems(treeItemVos);
        return treeVo;

    }

    private void recursionTree(List<TreeItemVo> treeItemVos, ResourceVo parent, List<ResourceVo> resourceVoList) {
        //构建目录对象
        TreeItemVo treeItem = new TreeItemVo();
        treeItem.setId(parent.getResourceNo());
        treeItem.setLabel(parent.getResourceName());

        //获得当前目录下子目录
        List<ResourceVo> children = resourceVoList.stream()
                .filter(n -> n.getParentResourceNo().equals(parent.getResourceNo()))
                .collect(java.util.stream.Collectors.toList());

        if (ObjectUtil.isNotEmpty(children)) {
            //递归调用子对象
            List<TreeItemVo> childrenTree = new ArrayList<>();
            //递归调用2,3级
            children.forEach(res -> {
                recursionTree(childrenTree, res, resourceVoList);
            });
            //设置子目录
            treeItem.setChildren(childrenTree);
        }
        //添加到集合中
        treeItemVos.add(treeItem);
    }

    /**
     * 资源添加
     *
     * @param resourceDto
     */
    @Override
    public void createResource(ResourceDto resourceDto) {
        Resource resource = new Resource();
        BeanUtil.copyProperties(resourceDto, resource);
        //查询父类资源
        Resource parent = resourceMapper.selectByResourceNo(resourceDto.getParentResourceNo());
        //将子类的状态设置为父类的状态
        resource.setDataState(parent.getDataState());

        //根据父资源编号生成资源编号
        String resourceNo = createResourceNo(resourceDto.getParentResourceNo());
        resource.setResourceNo(resourceNo);


        resourceMapper.createResource(resource);
    }


    //生成资源编号
    private String createResourceNo(String parentResourceNo) {
        //判断是否大于三级
        if (NoProcessing.processString(parentResourceNo).length() / 3 >= 5) {
            throw new BaseException(BasicEnum.RESOURCE_DEPTH_UPPER_LIMIT);
        }
        //查询父类资源是否包含子集
        Resource resourcebean = new Resource();
        resourcebean.setParentResourceNo(parentResourceNo);
        List<ResourceVo> resourceVoList = resourceMapper.resourceList(resourcebean);
        if (ObjectUtil.isEmpty(resourceVoList)) {
            return NoProcessing.createNo(parentResourceNo, false);
        }
        String max = resourceVoList.stream().map(r -> {
            return r.getResourceNo();
        }).max(Comparator.comparing(n -> n)).get();
        return NoProcessing.createNo(max, true);

    }

    /**
     * 资源修改
     *
     * @param resourceDto
     */
    @Override
    public void update(ResourceDto resourceDto) {
        Resource resource = new Resource();
        BeanUtil.copyProperties(resourceDto, resource);
        resourceMapper.update(resource);
    }

    /**
     * 启用禁用
     *
     * @param resourceDto
     */
    @Override
    public void enableDisable(ResourceDto resourceDto) {
        // 获取父资源编号
        String parentResourceNo = resourceDto.getParentResourceNo();
        // 根据父资源编号查询资源信息
        Resource resource = resourceMapper.selectByResourceNo(parentResourceNo);
        // 如果父资源存在且为启用状态，则抛出异常，表示操作无效
        if (resource.getDataState().equals("1")) {
            throw new BaseException(BasicEnum.PARENT_MENU_DISABLE);
        }

        // 获取当前资源编号
        String resourceNo = resourceDto.getResourceNo();
        // 更新当前资源的数据状态
        resourceMapper.updateByResourceNo(resourceNo, resourceDto.getDataState());
        // 更新所有子资源的数据状态，与父保存一致
        resourceMapper.updateByParentResourceNo(NoProcessing.processString(resourceNo), resourceDto.getDataState());


    }

    /**
     * 删除菜单
     *
     * @param resourceNo
     */
    @Override
    public void delete(String resourceNo) {
        if (hasChildResource(resourceNo)) {
            throw new RuntimeException("存在子菜单,不可删除！");
        } else {
            resourceMapper.delete(resourceNo);
        }

    }

    /**
     * 查看子类的数量
     */
    public boolean hasChildResource(String resourceNo) {
        int count = resourceMapper.selectOne(resourceNo);
        return count > 0;
    }

}
